import { connectToSalesforce, SalesforceConnection } from '../../src/salesforce/connection';
import { Connection as JsforceConnection } from 'jsforce';

import Chai from 'chai';
import Sinon from 'sinon';
import SinonChai from 'sinon-chai';
Chai.use(SinonChai);

const { expect } = Chai;

describe('SalesforceConnection', () => {
  const credentials = {
    username: 'username',
    password: 'password',
    loginUrl: 'https://loginUrl',
  };

  let loginStub: Sinon.SinonStub;

  before(() => {
    loginStub = Sinon.stub(JsforceConnection.prototype, 'login');
  });

  afterEach(() => {
    Sinon.reset();
  });

  it('stores connection with provided creds', async () => {
    const connection: SalesforceConnection = connectToSalesforce(credentials);
    const storedConnection: JsforceConnection = (connection as any).jsfConnection;
    expect((storedConnection as any).loginUrl).to.equal(credentials.loginUrl);
  });

  it('logs in when api requested', async () => {
    const connection: SalesforceConnection = connectToSalesforce(credentials);
    await connection.api();
    expect(loginStub).to.be.calledOnce;
    expect(loginStub).to.be.calledWith(credentials.username, credentials.password);
  });

  it('logs in only once when api requested multiple times', async () => {
    const connection: SalesforceConnection = connectToSalesforce(credentials);
    await connection.api();
    await connection.api();
    await connection.api();
    await connection.api();
    await connection.api();
    expect(loginStub).to.be.calledOnce;
  });
});
